package cn.topevery.garden.dal.logic;

import cn.topevery.garden.entity.dto.UpmsUserDTO;
import cn.topevery.garden.entity.po.Person;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.entity.DbCsp;
import hw.topevery.framework.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UpmsLogic {
    @Resource(name = "remoteRestTemplate")
    private RestTemplate restTemplate;
    @Autowired
    private SysUserLogic sysUserLogic;
    @Autowired
    private PersonLogic personLogic;

    @Value("${topevery.upmsUrl}")
    private String upmsUrl;

    @Value("${topevery.authUrl}")
    private String authUrl;

    @Value("${topevery.client_id}")
    private String client_id;

    @Value("${topevery.client_secret}")
    private String client_secret;

    public JsonResult<?> loginUpm(String token) {
        try {
            //校验用户是否有效
            token = "Bearer " + token;
            log.info("token:{}", token);
            UpmsUserDTO userInfoUpm = getUserInfoUpm(token);
            if (userInfoUpm == null || StringUtils.isBlank(userInfoUpm.getUserName())) {
                return JsonResult.error("未获取到用户信息");
            }
            log.info("userInfoUpm:{}", userInfoUpm);
            SysUser sysUser = sysUserLogic.getEntityByLoginName(userInfoUpm.getUserName());
            CompletableFuture<Void> addUserFuture = null;
            if (sysUser == null) {
                //用户不存在，新增用户
                addUserFuture = addUser(userInfoUpm);
            }
            HttpHeaders headers = new HttpHeaders();
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            //接口参数
            map.put("grant_type", Collections.singletonList("username"));
            map.put("client_id", Collections.singletonList("api-resource"));
            map.put("client_secret", Collections.singletonList("api#resource#123"));
            map.put("username", Collections.singletonList(userInfoUpm.getUserName()));
            //头部类型
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //构造实体对象
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
            if (addUserFuture != null) {
                addUserFuture.get(3, TimeUnit.SECONDS);
            }
            ResponseEntity<Map<String, Object>> responseEntity = restTemplate.exchange(authUrl, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<Map<String, Object>>() {
            });
            Map resultMap = responseEntity.getBody();
            if (CollectionUtils.isEmpty(resultMap)) {
                return JsonResult.error("oauth登录异常");
            }
            log.info("登录成功token：{}", resultMap.get("access_token"));
            return JsonResult.ok(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("服务器异常,token可能过期：{}", e.getMessage());
            return JsonResult.error("服务器异常,token可能过期！");
        }
    }

    private CompletableFuture<Void> addUser(UpmsUserDTO userInfoUpm) {
        return CompletableFuture.runAsync(() -> {
            //新增系统用户
            /*SysUser newUser = new SysUser();
            newUser.userId = UUID.randomUUID().toString().toUpperCase();
            newUser.userName = userInfoUpm.getNickName();
            newUser.loginName = userInfoUpm.getUserName();
            newUser.deptId = "835B6E1F-D9E7-42DB-A362-1317D8DBF8FB";
            newUser.mapId = "f41889ad-585b-413d-878e-7040991f468d";
            newUser.mapType = 13001;
            newUser.userIsAdmin = 0;
            newUser.createId = newUser.updateId = "53b39c3c-5d35-4393-aedf-b178a1da8a14";
            newUser.createTime = newUser.updateTime = LocalDateTime.now();
            newUser.dbStatus = false;
            newUser.userEmail = userInfoUpm.getEmail();
            String password = "Jiulongpo@2022";
            PasswordEncoder encoder = new BCryptPasswordEncoder(10);
            newUser.loginPassword = encoder.encode(password);
            sysUserLogic.insert("53b39c3c-5d35-4393-aedf-b178a1da8a14", newUser);
            Person person = new Person();
            person.setName(userInfoUpm.getNickName());
            person.setWorkState(2);
            person.setWorkStateDesc("在职");
            person.setDbStatus(false);
            person.setUserId(newUser.userId);
            personLogic.insert("10", person);
            log.info("loginName:{}", userInfoUpm.getUserName());*/
        });
    }

    private UpmsUserDTO getUserInfoUpm(String token) {
        HttpHeaders header = new HttpHeaders();
        header.set(HttpHeaders.AUTHORIZATION, token);
        header.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(header);
        ResponseEntity<JsonResult> responseEntity = restTemplate.exchange(upmsUrl + "/oauth/userinfo", HttpMethod.GET, httpEntity, JsonResult.class);
        JsonResult jsonResult = responseEntity.getBody();
        log.info("获取到统一平台的用户信息jsonResult:{}", jsonResult.data);
        return JSON.parseObject(JSON.toJSONString(jsonResult.data), UpmsUserDTO.class);
    }

    @Value("${topevery.appId}")
    private String appId;

    public boolean userSynchronize() {
        HttpHeaders header = new HttpHeaders();
        header.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Map<String, Object> map = new HashMap<String, Object>(1) {{
            put("appId", appId);
            put("isPage", true);
            put("current", 1);
            put("limit", 500);
        }};
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(map, header);
        ResponseEntity<JsonResult> response = restTemplate.exchange(upmsUrl + "/users", HttpMethod.POST, httpEntity, JsonResult.class);
        JsonResult result = response.getBody();
        if (!result.success) {
            return false;
        }
        List<UpmsUserDTO> upmsUserDTOS = JSON.parseObject(JSON.toJSONString(result.data), new TypeReference<List<UpmsUserDTO>>() {
        });
        //查询数据库已有用户
        List<String> loginNameList = sysUserLogic.getSearch(new DbCsp()).stream().map(u -> u.loginName).collect(Collectors.toList());
        /*List<SysUser> userShouldAdd = upmsUserDTOS.stream()
                .filter(dto -> !loginNameList.contains(dto.getAccount()))
                .map(dto -> {
                    //新增系统用户
                    SysUser newUser = new SysUser();
                    newUser.userId = UUID.randomUUID().toString().toUpperCase();
                    newUser.userName = dto.getNickName();
                    newUser.loginName = dto.getAccount();
                    newUser.deptId = "835B6E1F-D9E7-42DB-A362-1317D8DBF8FB";
                    newUser.mapId = "f41889ad-585b-413d-878e-7040991f468d";
                    newUser.mapType = 13001;
                    newUser.userType = 11001;
                    newUser.userIsAdmin = 0;
                    newUser.createId = newUser.updateId = "53b39c3c-5d35-4393-aedf-b178a1da8a14";
                    newUser.createTime = newUser.updateTime = LocalDateTime.now();
                    newUser.dbStatus = false;
                    newUser.userEmail = dto.getEmail();
                    newUser.userMobile = dto.getPhone();
                    newUser.userIdcard = dto.getIdcard();
                    String password = "Jiulongpo@2022";
                    PasswordEncoder encoder = new BCryptPasswordEncoder(10);
                    newUser.loginPassword = encoder.encode(password);
                    return newUser;
                }).collect(Collectors.toList());*/
/*        if (!CollectionUtils.isEmpty(userShouldAdd)) {
            sysUserLogic.insert("10", userShouldAdd);
            log.info("新增了{}个用户", userShouldAdd.size());
        }*/
        return true;
    }
}
